package com.perfectbeauties.admin.parser.sites;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.perfectbeauties.admin.parser.IParser;
import com.perfectbeauties.admin.parser.ParserUtil;

public class MetArtParser implements IParser {

	private static final String URL = "http://www.thelifeerotic.com/webmasters/image_galleries.html";
	private static final int SITE = 5;
	
	// Set to -1 or 0 to turn off sampling
	private static final int SAMPLE = -1;
	private static final boolean FIRST_RUN = false;
	
	public boolean parse() {
		
		try {
		
			URL url = new URL(URL);
	        URLConnection yc = url.openConnection();
	        BufferedReader in = new BufferedReader(
	                                new InputStreamReader(
	                                yc.getInputStream()));
	        
	        int galleryCount = 0;
	        
	        String line = in.readLine();
	        while (!line.contains("replace XXXXXXX with your ccbill affiliate code")) {
            	line = in.readLine();
            }
	        
	        while (line != null) {
	            while (!line.contains("<table width=\"710\"")) {
	            	line = in.readLine();
	            }
	            
	            while (!line.contains("geneva14ash")) {
	            	line = in.readLine();
	            }
	            
	            String name = line.substring(line.indexOf(">")+1,line.indexOf("</td>")).trim();
	            
	            while (!line.contains("geneva12grey")) {
	            	line = in.readLine();
	            }
	            
	            String desc = line.substring(line.indexOf(">")+1,line.indexOf("</td>")).trim();
	            
	            
	            while (!line.contains("genevaash10")) {
	            	line = in.readLine();
	            }
	            line = in.readLine();
	            while (!line.contains("genevaash10")) {
	            	line = in.readLine();
	            }
	            
	            String zip = line.substring(line.indexOf("href")+6,line.lastIndexOf("\">")).trim();
	            
	            String result = ParserUtil.submit(name, desc, SITE, zip);
	            
	            if (!FIRST_RUN && result.equals("Warning:Exists")) {
	            	break;
	            }
	            
				System.out.println(result+" ("+name+")");	
								
				line = in.readLine();
				
				galleryCount++;
				
				if (SAMPLE > 0 && galleryCount >= SAMPLE) {
					break;
				}
	            
	        }
	        in.close();
	        
	        return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
